
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_test_project/module/provider_test_page/xf_provider/xf_change_notifier_provider.dart';
import 'package:flutter_test_project/module/provider_test_page/xf_provider/xf_inherited_provider.dart';

import 'models/cart_model.dart';
import 'models/item.dart';

void main() => runApp(MaterialApp(
  home: ProviderTestPage(),
));

class ProviderTestPage extends StatefulWidget {
  @override
  State<StatefulWidget> createState() => _ProviderTestPageState();

}

class _ProviderTestPageState extends State<ProviderTestPage> {

  @override
  Widget build(BuildContext context) {
    return providerWidget(context);
  }

  Widget providerWidget(BuildContext context){
    return Center(
      child: XFChangeNotifierProvider<CartModel>(
        data: CartModel(),
        child: Builder(builder: (context) {
          return Column(
            children: <Widget>[
              Builder(builder: (context){
                var cart = XFChangeNotifierProvider.of<CartModel>(context);
                double totalPrice = 0;
                if (cart != null){
                  totalPrice = cart.totalPrice;
                }
                return Text("总价: $totalPrice");
                // return Text("总价: 100");
              }),
              Builder(builder: (context){
                print("RaisedButton build"); //在后面优化部分会用到
                return RaisedButton(
                  child: Text("添加商品"),
                  onPressed: () {
                    //给购物车中添加商品，添加后总价会更新
                    final card = XFChangeNotifierProvider.of<CartModel>(context);
                    if (card != null){
                      final item = Item(price: 20.0,count: 1);
                      card.add(item);
                    } else {
                      print("card is emptu");
                    }
                  },
                );
              }),
            ],
          );
        }),
      ),
    );
  }
  Widget inheritedWidget(BuildContext context){
    return Center(
      child: XFInheritedProvider( //使用ShareDataWidget
        data: CartModel(),
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Padding(
              padding: const EdgeInsets.only(bottom: 20.0),
              child: Text("12345"),//子widget中依赖ShareDataWidget
            ),
            RaisedButton(
              child: Text("Increment"),
              //每点击一次，将count自增，然后重新build,ShareDataWidget的data将被更新
              onPressed: (){
                // final card = XFInheritedProvider.of(context);
                // print("card is ${card == null ? "empty" : "not empty"}");
              },
            )
          ],
        ),
      ),
    );
  }

}